package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.constant.MessageConstant;
import com.atguigu.constant.RedisMessageConstant;
import com.atguigu.entity.Result;
import com.atguigu.pojo.Order;
import com.atguigu.service.OrderService;
import com.atguigu.utils.RedisConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * @Author LEO
 * @Date 2021年12月22日 12:59
 */
// 提交预约
@RestController
@RequestMapping("/pages/order")
public class OrderMobileController {


      @Reference
      private OrderService orderService;

      @Autowired
      private JedisPool jedisPool;
            /**
         * 旅游预约
         * @param map
         * @return
         */
    @RequestMapping("/submit")
     public Result submitOrder(@RequestBody Map map){
        // ① 在页面获取手机号
        String telephone = (String) map.get("telephone");
        //② 在页面获取验证码
        String validateCode = (String) map.get("validateCode");
        //从Redis中获取缓存的验证码，key为手机号+RedisMessageConstant.SENDTYPE_ORDER
        String  codeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        //校验手机验证码
        if (codeInRedis==null &&  !codeInRedis.equals(validateCode)){
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

        Result result =null;
        try {
            //调用旅游预约服务
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            result= orderService.saveOrder(map);
        } catch (Exception e) {
            e.printStackTrace();
            //预约失败
            return result;
        }
        return result;
    }


    //根据id查询预约信息，包括套餐信息和会员信息
    @PostMapping("/findById")
    public Result findById(Integer id){
        Map<String,Object> map =null;
        try {
            map = orderService.findById4Detail(id);
            //查询预约信息成功
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            //查询预约信息失败
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
